//「一本通 3.1 练习 3」秘密的牛奶运输
//求严格次小生成树的权值和
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int MAXN=500;
const int MAXM=10000;
int n,m;
struct Edge
{
   int u,v,w;
   bool operator<(const Edge other)const {
       return w<other.w;
   }
};
Edge edges[MAXM+1];
vector<int> G[MAXN+1][MAXN+1];
struct UFS_Node{
    int head,last,next,size;
};
struct UFS{
    UFS_Node ele[MAXN+1];
    void init(){
        for(int i=1;i<=n;i++) ele[i]={i,i,0,1};
    }
    int find_set(int x){
        return ele[x].head;
    }
    void addto(int hx,int hy){
       ele[ele[hx].last].next=hy;
       ele[hx].last=ele[hy].last;
       ele[hx].size+=ele[hy].size;
       while(hy>0){
           ele[hy].head=hx;
           hy=ele[hy].next;
       }
    }
    void union_set(int x,int y){
        int hx=find_set(x);
        int hy=find_set(y);
        if (hx!=hy){
            if (ele[hx].size>=ele[hy].size) addto(hx,hy);
            else addto(hy,hx);
        }
    }
};
UFS ufs;
long long ans;
int mininc=0x7fffffff;
int main(){
    cin>>n>>m;
    for(int i=0;i<m;i++){
        int u,v,w;
        cin>>u>>v>>w;
        edges[i]={u,v,w};
        G[u][v].push_back(w);
        G[v][u].push_back(w);
    }
    sort(edges,edges+m);
    ufs.init();
    
    for(int i=0;i<m;i++){
        int ru=ufs.find_set(edges[i].u);
        int rv=ufs.find_set(edges[i].v);
        if (ru!=rv){
            ans+=edges[i].w;
            int node1=ru;
            //枚举两个子集中的任意一对点，如果有边，求出每条边与当前边的权值差，找出最小差（0除外）
            while(node1!=0){
                int node2=rv;
                while(node2!=0){
                    int num=G[node1][node2].size();
                    if (num>0) {
                        for(int k=0;k<num;k++){
                            int inc =G[node1][node2][k]-edges[i].w;
                            if (inc>0&&inc<mininc) mininc=inc;
                        }
                    }
                    node2=ufs.ele[node2].next;
                }
                node1=ufs.ele[node1].next;
            }
            ufs.union_set(ru,rv);
        }
    }
    //cout<<ans<<endl;
    ans+=mininc;
    cout<<ans;
}

